package com.njcb.ams.support.security.service;

import com.njcb.ams.factory.domain.AppContext;
import com.njcb.ams.pojo.dto.standard.Response;
import com.njcb.ams.service.SsoClientService;
import com.njcb.ams.util.AmsJsonUtils;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.LoginUrlAuthenticationEntryPoint;

import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 用来解决匿名用户访问无权限资源时的异常
 *
 * @author liuyanlong
 */
public class CustomAuthenticationEntryPoint extends LoginUrlAuthenticationEntryPoint {
    public CustomAuthenticationEntryPoint(String loginFormUrl) {
        super(loginFormUrl);
    }

    @Override
    public void commence(final HttpServletRequest request, final HttpServletResponse response, final AuthenticationException authException) throws IOException, ServletException {
        SsoClientService ssoClientService = AppContext.getBean(SsoClientService.class);
        Boolean isSucc = ssoClientService.ssoHandle(request,response);
        if(isSucc){
            response.setCharacterEncoding("utf-8");
            response.setContentType("application/json;charset=utf-8");
            ServletOutputStream out = response.getOutputStream();
            out.write(AmsJsonUtils.objectToJson(Response.buildFail("403", "用户未认证或会话失效，请认证访问！")).getBytes("UTF-8"));
            out.flush();
        }else{
            ssoClientService.ssoRedirect(request,response);
        }
    }
}